/* internal/js/report/form.js */

function showHideInputBox () {
	var opt = document.getElementById('dwellingType');
	var val = opt.options[opt.selectedIndex].value;
	var buildingTb = document.getElementById('building');
	var roomTb = document.getElementById('room');
	
	var buildingTR = document.getElementById('buildingTR');
	var roomTR = document.getElementById('roomTR');
	
	
	if (val == 'Hotel' || val == 'Apartment') {
		buildingTR.style.display = 'table-row';
		roomTR.style.display = 'table-row';
		buildingTb.focus();
	}
	else if (val == 'Company Building') {
		
		buildingTR.style.display = 'table-row';
		roomTR.style.display = 'none';
		
		buildingTb.focus();
	}	
	else {
		buildingTR.style.display = 'none';
		roomTR.style.display = 'none';
		buildingTb.value = '';
		roomTb.value = '';
	}
}

function resetFields () {
	document.getElementById('deliveryID').value = '';
	document.getElementById('firstname').value = '';
	document.getElementById('lastname').value = '';
	document.getElementById('phone').value = '';
	document.getElementById('address').value = '';
	document.getElementById('city').value = '';
	document.getElementById('province').value = '';
	document.getElementById('postalCode1').value = '';
	document.getElementById('postalCode2').value = '';
	document.getElementById('dwellingType').selectedIndex = '0';
	document.getElementById('building').value = '';
	document.getElementById('room').value = '';
	document.getElementById('deliveryStatus').selectedIndex = '0';
	document.getElementById('instruction').value = '';
	
	hideFieldMessage('firstnameMessage');
	hideFieldMessage('lastnameMessage');
	hideFieldMessage('phoneMessage');
	hideFieldMessage('addressMessage');
	hideFieldMessage('cityMessage');
	hideFieldMessage('provinceMessage');
	hideFieldMessage('postalCodeMessage');
	hideFieldMessage('dwellingTypeMessage');
	
	selectResultRow(0);
	//TODO hide room, building tb
}

function loadPage () {
	//showHideInputBox();
}


/* To build result table */

function startResultsTable () {
	var html = '<table class="searchResults">' +
	           '<tr>' +
	           '<th>Receiver Name</th>' +
	           '<th>address</th>' +
	           '<th>Dwelling Type</th>' +
	           '<th>Status</th>' +
	           '<th></th>' +
	           '</tr>';
	return html;
}


function buildTable (deliveries) {
	var html = startResultsTable();
	var count = deliveries.childNodes.length;
	var ids = new Array(count);
	var showOptionAll = document.showOpForm.showOption[0].checked;
	var counter = 0;
	for (var loop = 0; loop < count; loop++) {
		var delivery = deliveries.childNodes[loop];
		var id = delivery.getElementsByTagName('id')[0].childNodes[0].nodeValue;
		var status = delivery.getElementsByTagName('status')[0].childNodes[0].nodeValue;
		
		// check the show option and decide whether to keep the info
		if (showOptionAll || status != 'Done')
		{
			ids[counter++] = id;
			
			var address = delivery.getElementsByTagName('address')[0].childNodes[0].nodeValue;
			var city = delivery.getElementsByTagName('city')[0].childNodes[0].nodeValue;
			var province = delivery.getElementsByTagName('province')[0].childNodes[0].nodeValue;
			var postalCode = delivery.getElementsByTagName('postal')[0].childNodes[0].nodeValue;
			var firstname = delivery.getElementsByTagName('firstname')[0].childNodes[0].nodeValue;
			
			var lastname;
			if (delivery.getElementsByTagName('lastname')[0].childNodes.length == 0)
				lastname = '';
			else
				lastname = delivery.getElementsByTagName('lastname')[0].childNodes[0].nodeValue;
			var phone = delivery.getElementsByTagName('phone')[0].childNodes[0].nodeValue;
			var dwelling = delivery.getElementsByTagName('dwelling')[0].childNodes[0].nodeValue;
			
			var roomNo;
			if (delivery.getElementsByTagName('room')[0].childNodes.length == 0)
				roomNo = '';
			else
				roomNo = delivery.getElementsByTagName('room')[0].childNodes[0].nodeValue;

			var buildingName;
			if (delivery.getElementsByTagName('building')[0].childNodes.length == 0)
				buildingName = '';
			else
				buildingName = delivery.getElementsByTagName('building')[0].childNodes[0].nodeValue;
			
			var instruction;
			if (delivery.getElementsByTagName('instruction')[0].childNodes.length == 0)
				instruction = '';
			else
				instruction = delivery.getElementsByTagName('instruction')[0].childNodes[0].nodeValue;
			
			html += addResultRow(id, address, city, province, postalCode, firstname, lastname, phone,
					dwelling, roomNo, buildingName, instruction, status);
		}
	}
	var newIds = new Array(counter);
	for (var i = 0; i < counter; i++)
		newIds[i] = ids[i];

	html += endResultsTable(newIds);
	return html;
}

function addResultRow (id, address, city, province, postalCode, firstname, lastname, phone, dwelling, roomNo, buildingName, instruction, status) {
	var	html =
		'<form id="listDeliveryForm' + id + '">' +
		'<input id="address" value="' + address + '" type="hidden" />' +
		'<input id="city" value="' + city + '" type="hidden" />' +
		'<input id="province" value="' + province + '" type="hidden" />' +
		'<input id="postalCode" value="' + postalCode + '" type="hidden" />' +
		'<input id="firstname" value="' + firstname + '" type="hidden" />' +
		'<input id="lastname" value="' + lastname + '" type="hidden" />' +
		'<input id="phone" value="' + phone + '" type="hidden" />' +
		'<input id="dwelling" value="' + dwelling + '" type="hidden" />' +
		'<input id="room" value="' + roomNo + '" type="hidden" />' +
		'<input id="building" value="' + buildingName + '" type="hidden" />' +
		'<input id="instruction" value="' + instruction + '" type="hidden" />' +
		'<input id="status" value="' + status + '" type="hidden" />' +
		'</form>' +
		'<tr id="listdeliveryRow' + id + '" class="searchResultsRow" onclick="showResult(\'' + id + '\')">' +
		'<td>' + firstname + " "+ lastname  + '</td>' +
		'<td>' + address + '</td>' +
		'<td>' + dwelling + '</td>' +
		'<td>' + status + '</td>' +
		'<td><input type="submit"';
	if (status != 'Done')
		html += ' value="Flag as Complete" name="flag" onclick="flagAsComplete(\'' + id + '\')" ></td></tr>';
	else
		html += ' value="Flag as Not Ready" name="flag" onclick="flagAsComplete(\'' + id + '\')" ></td></tr>';
	return html;
}

function endResultsTable (ids) {
	var html =
		'<input id="resultsIds" value="' + ids.join() +'" type="hidden" />' + 
		'</table>';
	return html;
}


function selectResultRow (id) {
	var ids = document.getElementById('resultsIds').value.split(',');
	var count = ids.length;
	for (var loop = 0; loop < count; loop++) {
		document.getElementById('listdeliveryRow' + ids[loop]).className = 'searchResultsRow';
	}
	try {
		document.getElementById('listdeliveryRow' + id).className = 'selectedResultsRow';
	} catch (e) {
	}
}

function showResult (id) {	
	selectResultRow(id);
	// TODO display roomNo, building
	var frm = document.getElementById('listDeliveryForm' + id);
	
	document.getElementById('deliveryID').value = id;
	document.getElementById('firstname').value = frm.firstname.value;
	document.getElementById('lastname').value = frm.lastname.value;
	document.getElementById('phone').value = frm.phone.value;
	document.getElementById('address').value = frm.address.value;
	document.getElementById('city').value = frm.city.value;
	document.getElementById('province').value = frm.province.value;
	
	var pos = frm.postalCode.value;
	document.getElementById('postalCode1').value = pos.substring(0,3);
	document.getElementById('postalCode2').value = pos.substring(3);
	
	var dwellingList = document.getElementById('dwellingType');
	var dwelling = frm.dwelling.value;
	for (var loop = 0; loop < dwellingList.length; loop++) {
		if (dwellingList.options[loop].value == dwelling) {
			dwellingList.selectedIndex = loop;
			break;
		}
	}
	var statusList = document.getElementById('deliveryStatus');
	var status = frm.status.value;
	for (var loop = 0; loop < statusList.length; loop++) {
		if (statusList.options[loop].value == status){
			statusList.selectedIndex = loop;
			break;
		}
	}
	showHideInputBox();
	document.getElementById('building').value = frm.building.value;
	document.getElementById('room').value = frm.room.value;
	
	document.getElementById('instruction').value = frm.instruction.value;
	
	//clearResults();
}

var menuDivs = new Array();
menuDivs[0] = "report1";
menuDivs[1] = "report2";
menuDivs[2] = "report3";

function getMenuDivs() {
	return menuDivs;
}

function changeMenuView(menuClass, divID) {

	var menuList, i;

	// Check that parameters are not null
	if (menuClass == null || divID == null)
		return;
		
	// Switch the "activeTab"
	menuList = document.getElementsByTagName("A");

	for (i = 0; i < menuList.length; i++) {
		if(menuList[i] == menuClass) {
			menuList[i].className += " activeTab";
			menuList[i].blur();
		}
		else
			resetActiveClass(menuList[i], "activeTab");
	}
	
	// Change the menuDiv being displayed
	flipMenuPage(divID);	
}

function changePageView(pageClass, menuDiv) {

	var pageList, i;

	// Check that parameters are not null
	if (pageClass == null || menuDiv == null)
		return;
		
	// Switch the "activePage"
	pageList = document.getElementsByTagName("A");

	for (i = 0; i < pageList.length; i++) {
		if(pageList[i] == pageClass) {
			pageList[i].className += " activePage";
			pageList[i].blur();
		}
		else
			resetActiveClass(pageList[i], "activePage");
	}
	
	// Change the menuDiv being displayed
	flipMenuPage(menuDiv);
}

function flipMenuPage(menuDiv) {
	var divList, i;

	// Check that the parameter is not null
	if (menuDiv == null)
		return;
		
	// Switch the menu page being viewed
	divList = getMenuDivs();

	for (i = 0; i < divList.length; i++) {
		if(divList[i] == menuDiv) {
			document.getElementById(divList[i]).style.display = "block";
		}
		else {
			document.getElementById(divList[i]).style.display = "none";
		}
	}
}

function resetActiveClass(el, name) {

	var i, curList, newList;

	// Reset the tab class

	newList = new Array();
	curList = el.className.split(" ");
	for (i = 0; i < curList.length; i++)
		if (curList[i] != name)
			newList.push(curList[i]);
	el.className = newList.join(" ");
}

/* Build Cost-Profit Report Table */

function startCostProfitResultsTable () {
        var html = '<table class="searchResults">' +
                   '<tr>' +
                   '<th> Name </th>' +
                   '<th> Total Cost </th>' +
                   '<th> Sales Revenue </th>' +
                   '<th> Gross Profit </th>' +
                   '</tr>';
        return html;
}


function buildCostProfitTable (reports) {
        var html = startCostProfitResultsTable();
        var count = reports.childNodes.length;
        var ids = new Array(count);

        for (var loop = 0; loop < count; loop++) {
                var report = reports.childNodes[loop];
                var id = report.getElementsByTagName('id')[0].childNodes[0].nodeValue;
                
                ids[loop] = id;
                                
                var name;
                if (report.getElementsByTagName('name')[0].childNodes.length == 0)
                        name = '';
                else
                        name = report.getElementsByTagName('name')[0].childNodes[0].nodeValue;
                
                var cost;
                if (report.getElementsByTagName('cost')[0].childNodes.length == 0)
                        cost = '';
                else
                        cost = report.getElementsByTagName('cost')[0].childNodes[0].nodeValue;
                
                var salesRev;
                if (report.getElementsByTagName('sales-revenue')[0].childNodes.length == 0)
                        salesRev = '';
                else
                        salesRev = report.getElementsByTagName('sales-revenue')[0].childNodes[0].nodeValue;
                
                var grossPro;
                if (report.getElementsByTagName('gross-profit')[0].childNodes.length == 0)
                        grossPro = '';
                else
                        grossPro = report.getElementsByTagName('gross-profit')[0].childNodes[0].nodeValue;
                
                html += addCostProfitResultRow(id, name, cost, salesRev, grossPro);
        
        }
        
        html += endCostProfitResultsTable(ids);
        return html;
}

function addCostProfitResultRow (id, name, cost, salesRev, grossPro) {
        var     html =
                '<tr>' +
                '<td align="center">' + name + '</td>' +
                '<td align="right">$' + cost + '</td>' +
                '<td align="right">$' + salesRev + '</td>' +
                '<td align="right">$' + grossPro + '</td></tr>';
        return html;
}

function endCostProfitResultsTable (ids) {
        var html =
                '<input id="resultsIds" value="' + ids.join() +'" type="hidden" />' + 
                '</table>';
        return html;
}

/* END Build Cost-Profit Report Table */


/* Build Sales Per Time Period Results Table */

function buildSalesPerTimePeriodResultsTable(report) {
	var title;
	if (report.getElementsByTagName('title')[0].childNodes.length == 0)
		title = '';
	else
		title = report.getElementsByTagName('title')[0].childNodes[0].nodeValue;
	
	var timePeriod;
	if (report.getElementsByTagName('timeperiod')[0].childNodes.length == 0)
		timePeriod = '';
	else
		timePeriod = report.getElementsByTagName('timeperiod')[0].childNodes[0].nodeValue;
	
	var html = '<h3>'+title+'</h3><br />';
	html += '<table>' +
			'<tr><th>Menu Item</th><th>Sales</th><th>'+timePeriod+'</th></tr>';
	
	var menuitems;
	if (report.getElementsByTagName('menuitems')[0].childNodes.length == 0)
		menuitems = '';
	else
		menuitems = report.getElementsByTagName('menuitems')[0].childNodes[0].nodeValue;
	
	var count = report.getElementsByTagName('menuitems')[0].childNodes.length;
	
	if(count == 0) {
		html += '<tr><td colspan="3">No Results</td></tr>';
	}
	
	for (var loop = 0; loop < count; loop++) {
		var menuitem = report.getElementsByTagName('menuitems')[0].childNodes[loop];
		var name = menuitem.getElementsByTagName('name')[0].childNodes[0].nodeValue;
		var total = menuitem.getElementsByTagName('total')[0].childNodes[0].nodeValue;
		var period = menuitem.getElementsByTagName('period')[0].childNodes[0].nodeValue;
		
		html += '<tr><td>'+name+'</td>' +
				'<td>'+total+'</td>' +
				'<td>'+period+'</td></tr>';
	}
	
	var reportTotal;
	if (report.getElementsByTagName('reporttotal')[0].childNodes.length == 0)
		reportTotal = '';
	else {
		reportTotal = report.getElementsByTagName('reporttotal')[0].childNodes[0].nodeValue;
		html += '<tr><th>Total</th><td>'+reportTotal+'</td><td></td></tr>';
	}
	
	return html;
}

/* END Buld Sales Per Time Period Results Table */

/* Print Report */

function printReport() {
	window.print();
}

/* END Print Report */